package dao.impl;

import java.util.ArrayList;

import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import dao.IVariableDAO;
import entities.Variable;

public class VariableDAO implements IVariableDAO {

	private HibernateBase hibernateBase;

	public VariableDAO() {
		hibernateBase = HibernateBase.getInstance();
	}

	@Override
	public void init() {
		hibernateBase.init();
	}

	@Override
	public void close() {
		hibernateBase.close();
	}

	@Override
	public boolean create(Variable variable) {
		boolean status = false;

		EntityTransaction tx = hibernateBase.getManager().getTransaction();
		try {
			tx.begin();
			hibernateBase.getManager().persist(variable);
			tx.commit();
			status = true;
		} catch (Exception e) {
			e.printStackTrace();
			if (tx.isActive()) {
				tx.rollback();
			}
		}
		return status;
	}

	@Override
	public boolean delete(Variable variable) {
		// TODO Auto-generated method stub
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ArrayList<Variable> getAll() {
		String queryString = "SELECT v FROM Variable v";

		Query query = hibernateBase.getManager().createQuery(queryString);
		ArrayList<Variable> variables = (ArrayList<Variable>) query
				.getResultList();

		return variables;
	}

	@Override
	public Variable getBy(long id) {
		Variable variable = hibernateBase.getManager().find(Variable.class, id);
		return variable;
	}

	@Override
	public boolean update(Variable variable) {
		boolean status = false;

		EntityTransaction tx = hibernateBase.getManager().getTransaction();
		try {
			tx.begin();
			hibernateBase.getManager().merge(variable);
			tx.commit();
			status = true;
		} catch (Exception e) {
			e.printStackTrace();
			if (tx.isActive()) {
				tx.rollback();
			}
		}
		return status;
	}

}
